﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Common.Util;
using ST.WX.Common;
using ST.WX.Common.Enums;
using ST.WX.Common.Model;
using ST.WX.XCX.SubscribeMsg.Model;
using System;
using System.Collections.Generic;

namespace ST.WX.XCX.SubscribeMsg
{
	/// <summary>
	/// 订阅消息接口
	/// </summary>
	public class WXSubscribeMsgApi
	{
		private readonly ILogger logger;
		private readonly WXBaseApi baseApi;

		public WXSubscribeMsgApi(ILogger<WXSubscribeMsgApi> _logger, WXBaseApi _baseApi)
		{
			logger = _logger;
			baseApi = _baseApi;
		}

		/// <summary>
		/// 发送模板消息
		/// </summary>
		/// <param name="appID"></param>
		/// <param name="openID">接收者（用户）的 openid</param>
		/// <param name="tplID">所需下发的模板消息的id</param>
		/// <param name="pageUrl">点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。</param>
		/// <param name="data">模板内容，不填则下发空模板</param>
		/// <returns></returns>
		public void Send(string appID, string appSecret, string openID, string tplID, string pageUrl, JObject data)
		{
			try
			{
				if (logger.IsEnabled(LogLevel.Debug))
				{
					logger.LogDebug("参数->appID:{0},openID:{1},tplID:{2},pageUrl:{3},data:[{4}]",
						appID, openID, tplID, pageUrl, data);
				}

				var paras = new JObject {
					{ "touser", openID },
					{ "template_id", tplID },
					{ "page", pageUrl }
				};

				if (data != null)
				{
					JObject paramData = new JObject();
					foreach (var item in data)
					{
						paramData.Add(item.Key, new JObject { { "value", item.Value } });
					}
					paras.Add("data", paramData);
				}

				string respText = HttpHelper.Post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + baseApi.GetAccessToken(appID, appSecret), paras.ToString());
				if (string.IsNullOrEmpty(respText))
				{
					throw new WXException("发送订阅消息失败，返回内容为空");
				}
				var ret = Newtonsoft.Json.JsonConvert.DeserializeObject<WXSubscribeMsgResult>(respText);
				if (ret.errcode != (int)WXErrorCode.请求成功)
				{
					throw new WXException(ret.errmsg);
				}
			}
			catch (WXException ex)
			{
				logger.LogError(ex, "发送订阅消息出错");
				throw;
			}
			catch (Exception ex)
			{
				logger.LogError(ex, "发送订阅消息出错");
				throw new WXException("发送订阅消息失败，" + (ex.InnerException != null ? ex.InnerException.Message : ex.Message));
			}
		}
	}
}
